package controller;

import model.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-25
 * Time：16:28
 */
@WebServlet("/following")
public class FollowingServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");

        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("用户未登陆，请登录！！");
            return;
        }
        //将user属性从session中取出
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("用户未登陆，请登录！！");
            return;
        }
        UserDao userDao = new UserDao();

        String followingUserId = req.getParameter("followingUserId");
        //构造following对象
        Following following = new Following();
        int uId = user.getUserId();
        following.setUserId(uId);
        int fId = Integer.parseInt(followingUserId);
        following.setFollowingUserId(fId);
        //构造follower对象
        Follower follower = new Follower();
        follower.setUserId(fId);
        follower.setFollowerUserId(uId);

        //如果关注的人是自己则失败
        if (fId == uId) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("你太自恋啦！不能关注自己哦～");
            return;
        }
        //如果已经关注，则失败
        FollowingDao followingDao = new FollowingDao();
        FollowerDao followerDao = new FollowerDao();
        if (!followingDao.check(following)) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("你已经关注过该用户啦！");
            return;
        }

        //将关注的对象从数据库中取出
        User followingUser =  userDao.selectById(fId);
        //更新user信息
        user = userDao.selectById(user.getUserId());

        //更新用户表里的followingCount和followerCount字段
        int followingOrigin = user.getFollowingCount();
        int followerOrigin = followingUser.getFollowerCount();
        //更新用户的关注数
        userDao.updateFollowingCount(uId, followingOrigin + 1);
        //更新作者的被关注数
        userDao.updateFollowerCount(fId, followerOrigin + 1);

        followingDao.insert(following);
        followerDao.insert(follower);
        String blogId = req.getParameter("blogId");
        resp.sendRedirect("blog_detail.html?blogId="+blogId);
    }
}
